import React from 'react';
import { message, Modal } from 'antd';
import {WeaErrorPage, WeaTools, WeaRightMenu, WeaLocaleProvider} from 'ecCom';
const { ls } = WeaTools;
import { isEqual } from 'lodash';
import PortalSetting from './PortalSetting';
const getLabel = WeaLocaleProvider.getLabel;
//引入元素组件
import LayoutFlags from './LayoutFlags';
import objectAssign from 'object-assign';
import { handlePortalSynize, onShowOrHideAllE, openFavouriteBrowser, showHelp } from '../util/rcmenu';
//门户组件
class Homepage extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            hpdata: null,
            params: {},
            isShrink: false,
        }
        this.handleParams = this.handleParams.bind(this);
        this.getPortalData = this.getPortalData.bind(this);
        this.getRightMenu = this.getRightMenu.bind(this);
        this.onRightMenuClick = this.onRightMenuClick.bind(this);
        this.handleAddElement = this.handleAddElement.bind(this);
        this.handleRefresh = this.handleRefresh.bind(this);
        this.onChangeLabel = this.onChangeLabel.bind(this);
        window.portalGetElementStyle = this.getPortalData.bind(this);
    }
    handleParams(props){
        let query = {};
        if(props.location) query = props.location.query
        let params = objectAssign({},props.params,query);
        if(props.hpid) {
            if(props.formData && typeof props.formData === 'object') props.formData = JSON.stringify(props.formData);
            params = objectAssign(params, props);
            if(!params.isSetting) params.isSetting = false;
        }else{
            params.isSetting = false;
            params.isfromportal = 1;
            params.isfromhp = 0;
        }
        window.element_custompage_loadIframe = params.loadIframe != 'false';
        return params;
    }
    getPortalData(params){
        if(params.isSaveElement){
            params = this.handleParams(this.props);
        }
        const { hpid, isSetting, isPortalRefresh } = params;
        const hpdata = ls.getJSONObj('portal-'+hpid+'-'+isSetting);
        // 标准登录后页面才使用缓存
        if (window.parseInt(hpid) > 0 && hpdata && this.state.params.hpid != hpid) {
            hpdata.islsdata = true;
            this.setState({ hpdata, params });
        }
		if(isPortalRefresh){
            this.timestamp = new Date().getTime();
        }
        WeaTools.callApi('/api/portal/homepage/hpdata', 'POST', params).then(data => {
            if(data.status === 'failed'){
                message.error(data.errormsg);
            }else{
                if(window.parseInt(hpid) > 0) {
                    ls.set('portal-'+hpid+'-'+isSetting, data);
                }
                this.timestamp = new Date().getTime();
                this.setState({ hpdata: data, params });
            }
        });
    }
    handleRefresh(nParams){
        const params = this.handleParams(this.props);
        this.getPortalData({...params,...nParams});
    }
    handleAddElement(element, areaflag, index){
        const { hpid, isSetting } = this.state.params;
        //获取当前设置门户信息
        let hpdata = {...this.state.hpdata};
        const layoutFlags = hpdata.hpinfo.layoutFlags;
        for (var i = 0; i < layoutFlags.length; i++) {
            let layoutFlag = layoutFlags[i];
            if(layoutFlag.areaflag === areaflag){
                let areaElements = layoutFlag.areaElements;
                areaElements.splice(index, 0, element.config);
                break;
            }
        }
        hpdata.hpCss += element.eCss;
        ls.set('portal-'+hpid+'-'+isSetting, hpdata);
        this.setState({
            hpdata,
        });
    }
    getHpRefreshData(params) {
        clearInterval(this.portalRefreshInterval);
        WeaTools.callApi('/api/portal/portalSetting/getHpRefreshData', 'GET').then(result => {
            const {data = {}} = result;
            const {needRefresh, refreshMins = 999, refreshEbaseid, refreshType} = data;
            if (needRefresh) {
                if(refreshType == '1'){
                    this.portalRefreshInterval = setInterval(()=>this.getPortalData({...params, isPortalRefresh: true}), refreshMins*60*1000);
                }else if(refreshType == '2'){
                    const refreshEbaseidArr = refreshEbaseid.split(',');
                    this.portalRefreshInterval = setInterval(() => {
                        //未读文档元素刷新
                        refreshEbaseidArr.indexOf("6") > -1 && window.element_unReadDoc_reLoad_all();
                        //流程元素刷新
                        refreshEbaseidArr.indexOf("8") > -1 && window.element_workflow_reLoad();
                        //文档中心元素刷新
                        refreshEbaseidArr.indexOf("7") > -1 && window.element_news_reLoad_all()
                    }, refreshMins*60*1000);
                }
            }
        });
    }
    componentWillMount(){
        const params = this.handleParams(this.props);
        this.getPortalData(params);
        this.getHpRefreshData(params);
    }
    componentWillUnmount() {
        clearInterval(this.portalRefreshInterval);
    }
    componentDidUpdate() {
        if(this.refs.btnWfCenterReload) this.refs.btnWfCenterReload.setAttribute("onclick","element_workflow_reLoad()");
    }
    componentDidMount(){
        const params = this.handleParams(this.props);
        if(this.refs.btnWfCenterReload) this.refs.btnWfCenterReload.setAttribute("onclick","element_workflow_reLoad()");
        if(this.refs.homepageContainer) $(this.refs.homepageContainer).css("min-height", $(".homepage[data-isSetting="+params.isSetting+"]").height());
        $(window).resize(() => {          //当浏览器大小变化时
            if(this.refs.homepageContainer) $(this.refs.homepageContainer).css("min-height", $(".homepage[data-isSetting="+params.isSetting+"]").height());
        });
    }
    componentWillReceiveProps(nextProps) {
        const params = this.handleParams(this.props);
        const nParams = this.handleParams(nextProps);
        if(window.isPortalRender || !isEqual(this.props, nextProps) || !isEqual(params, nParams)){
            this.getPortalData(nParams);
            this.getHpRefreshData(nParams);
        }
    }
    render() {
        const { isSynergySetting, synergyParams, location } = this.props;
        const { params, hpdata } = this.state;
        if(params.hpid){
            let style = {};
            let hpHtml = <div/>;
            let styleStr = "";
            const { hpid, subCompanyId, isSetting } = params;
            let layoutid = '';
            if(hpdata){
                if(hpdata.hasRight){
                    layoutid = hpdata.hpinfo.bLayoutid;
                    style = {background: hpdata.hpinfo.bgcolor}
                    let queryParams = {};
                    if(location) queryParams = location.query;
                    const layoutObj = {
                        config: {
                            isRender: true,
                            timestamp: this.timestamp,
                            islsdata: !!hpdata.islsdata,
							from:params.from,
                            isremembertab: hpdata.hpinfo.isremembertab,
                            isSetting: hpdata.hpinfo.isSetting,
                            userid: hpdata.hpinfo.userid,
                            isSynergySetting: isSynergySetting,
                            synergyParams: objectAssign({}, synergyParams, queryParams)
                        },
                        layoutFlags: hpdata.hpinfo.layoutFlags,
                        layoutid: hpdata.hpinfo.bLayoutid,
                        layoutHtml: hpdata.hpinfo.html
                    };
                    styleStr = hpdata.hpCss.replace(/\"/g, "");
                    hpHtml = <LayoutFlags ecId={`${this && this.props && this.props.ecId || ''}_LayoutFlags@6k42ko`} {...layoutObj}/>
                }else{
                    hpHtml = <NoRightPage ecId={`${this && this.props && this.props.ecId || ''}_NoRightPage@kx0lms`} msg={hpdata.msg}/>;
                }
            }

            if (parseInt(hpid) < 0) { // 流程表单协同可能存在多个门户
                if (jQuery(`#portal-style-${hpid}`) && jQuery(`#portal-style-${hpid}`).length) {
                    jQuery(`#portal-style-${hpid}`).html(styleStr);
                } else {
                    jQuery(jQuery('head')[0]).append(`<style id="portal-style-${hpid}" type="text/css">${styleStr}</style>`);
                }
            } else {
                if (jQuery(`#portal-style`) && jQuery(`#portal-style`).length) {
                    jQuery(`#portal-style`).html(styleStr);
                } else {
                    jQuery(jQuery('head')[0]).append(`<style id="portal-style" type="text/css">${styleStr}</style>`);
                }
            }

            let classname = 'homepage';
            if(isSetting) {
                classname = 'homepage homepage-setting'
            }
            return <div className={classname}
                        data-hpid={hpid} 
                        data-subcompanyid={subCompanyId} 
                        data-issetting={isSetting} 
                        data-layoutid={layoutid}
                        style={style}>
                {!isSetting ? <PortalSetting ecId={`${this && this.props && this.props.ecId || ''}_PortalSetting@jt47pm`} ref="portalsetting"/> : ''}
                <div style={{margin:'-10px -10px 0 0'}}>
                    <input type="hidden" ref="btnWfCenterReload" value="btnWfCenterReload" id="btnWfCenterReload" name="btnWfCenterReload"/>
                    {isSetting ? hpHtml : <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@rriagw`} datas={this.getRightMenu()} onClick={this.onRightMenuClick}>
                        <div ref="homepageContainer" style={{height: '100%'}}>{hpHtml}</div>
                    </WeaRightMenu>}
                </div>
            </div>
        } else {
            return <div className='homepage'></div>;
        }
    }
    getRightMenu(){
        let btns = [];
        const { hpdata } = this.state;
        if(hpdata){
            hpdata.rcmenu.map(menu=>{
                btns.push({
                    key: menu.key,
                    icon: <i className={menu.icon}/>,
                    content: menu.label,
                }); 
            });
        }
        return btns
    }
    onRightMenuClick(key){
        const { params, hpdata } = this.state;
        let _params = {...params};
        _params.isSetting = true;
        _params.viewtype = 'edit';
        _params.from = 'addElement';
        _params.isfromportal = undefined;
        _params.title = hpdata.hpinfo.hpname;
        switch(key){
            case 'resethp':
            case 'updatesynihp':
            case 'completesynihp':
                handlePortalSynize({
                    hpid: _params.hpid,
                    subCompanyId: _params.subCompanyId,
                    method: key
                });
                break;
            case 'shrinkAll':
                this.setState({
                    isShrink: !this.state.isShrink
                });
                this.onChangeLabel(this.state.hpdata.rcmenu,'shrinkAll', this.state.isShrink);
                onShowOrHideAllE(params.isSetting);
                break;
            case 'settingElement':
                window.handlePortalSetting(_params);    
                break;
            case 'store':
                openFavouriteBrowser();
                break;
            case 'help':
                showHelp();
                break;
            case '5':
                break;
        }
    }
    onChangeLabel(rcmenu, key , bool){
        let lable1 = getLabel(18466,'全部收缩');
        let lable2 = getLabel(16216,'全部展开');
        rcmenu.map(item => {
            if(item.key == key){
                if(bool){
                    item.label = lable1;
                    item.icon = "icon-coms-All-contraction"
                }else{
                    item.label = lable2;
                    item.icon = "icon-coms-All-unfolding"
                }
            }
        })
    }
}
 //无权限门户
 const NoRightPage = ({ msg }) =>
     <div className = "page-noright">
         <img src = "/images/ecology8/noright_wev8.png" width = "162px" height = "162px" />
         <div style = {{ color: 'rgb(255,187,14)' } }>{msg}</div>
     </div>

class MyErrorHandler extends React.Component {
    render() {
        const hasErrorMsg = this.props.error && this.props.error !== "";
        return ( <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@ro2rax`} msg = { hasErrorMsg ? this.props.error :getLabel(385218,"对不起，该页面异常，请联系管理员！") }/>
        );
    }
}

Homepage = WeaTools.tryCatch(React, MyErrorHandler, { error: "" })(Homepage);
export default Homepage;
